package com.education.platform.api.controller.user;

import com.alibaba.fastjson.JSON;
import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.LoginService;
import com.education.platform.api.service.UserBaseService;
import com.education.platform.api.service.entity.LoginSuccessDTO;
import com.education.platform.api.vo.request.CommitInviteCodeVO;
import com.education.platform.api.vo.request.LoginRequestVO;
import com.education.platform.api.vo.request.UserBaseUpdateVO;
import com.education.platform.api.vo.request.VersionAndDeviceVO;
import com.education.platform.api.vo.response.LoginResponseVO;
import com.education.platform.common.redis.RedisUtils;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.common.util.ValidatorUtils;
import com.education.platform.dao.entity.UserBaseDO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
* describe: 前端用户基础表
* @author : tomato
* @date: 2020-06-07 11:38:44.106
**/
@RestController
@Api("个人中心")
@RequestMapping("userBase")
@Validated
public class UserBaseController {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseController.class);
    
	@Autowired
    private UserBaseService userBaseService;

	@Autowired
    private LoginService loginService;
    @Value("${token.expire}")
    private int tokenExpire;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取用户信息
     * @param
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @PostMapping("getUserInfo")
    public LoginResponseVO getUserInfo() {
        UserBaseDO user = ThreadUser.getUser(UserBaseDO.class);
        LoginSuccessDTO successDTO =loginService.buildLoginSuccess(user);
        if(StringUtils.isEmpty(successDTO.getCode())){
            String code = loginService.saveInviteCode(user.getId());
            successDTO.setCode(code);
            user.setCode(code);
            redisUtils.setString(ThreadUser.getUserTokenRedisKey(),tokenExpire, JSON.toJSONString(user));
        }
        if(successDTO.getGuide() == null){
            successDTO.setGuide(Boolean.FALSE);
        }
        successDTO.setToken(ThreadUser.getRequestToken());
        return BeanUtil.convert(successDTO, LoginResponseVO.class);
    }


    /**
     * 修改个人资料
     * @param
     * @return 修改个人资料
     */
    @ApiOperation(value = "修改个人资料")
    @PostMapping("editInformation")
    public void editInformation(@RequestBody @Valid UserBaseUpdateVO updateVO) {
         userBaseService.editInformation(updateVO);
    }


    /**
     * 修绑定手机号
     * @param
     * @return
     */
    @ApiOperation(value = "绑定手机号")
    @PostMapping("bindingPhone")
    public boolean bindingPhone(@RequestBody @Valid LoginRequestVO requestVO) {
        ValidatorUtils.isMobile(requestVO.getPhone());
        return loginService.bindingPhone(requestVO.getPhone(),requestVO.getVerificationCode());
    }


    /**
     * 提交邀请码
     * @param
     * @return
     */
    @ApiOperation(value = "提交邀请码")
    @PostMapping("commitInviteCode")
    public void editInformation(@RequestBody @Valid CommitInviteCodeVO inviteCodeVO) {
        userBaseService.commitInviteCode(inviteCodeVO.getCode());
    }



    /**
     * 版本/设备号
     * @param
     * @return
     */
    @ApiOperation(value = "版本/设备号")
    @PostMapping("updateVersion")
    public void updateVersion(@RequestBody  VersionAndDeviceVO vo) {
        UserBaseDO user = ThreadUser.getUser(UserBaseDO.class);
        //版本 设备
        try {
            String device = vo.getDevice();
            String version = vo.getVersion();
            if (device != null || version != null) {
                UserBaseDO versionUpdate = new UserBaseDO();
                versionUpdate.setId(user.getId());
                boolean change=false;
                if(device != null&&!device.equals(user.getDevice())){
                    versionUpdate.setDevice(vo.getDevice());
                    user.setDevice(device);
                    change=true;
                }
                if(version != null&&!version.equals(user.getVersion())){
                    versionUpdate.setVersion(version);
                    user.setVersion(version);
                    change=true;
                }
                if(change){
                    userBaseService.updateVersion(versionUpdate);
                    redisUtils.setString(ThreadUser.getUserTokenRedisKey(),tokenExpire, JSON.toJSONString(user));
                }
            }
        } catch (Exception e) {
            LOGGER.error("修改版本异常："+e.getMessage());
        }
    }

}
